import type { NavigationGuardNext, RouteLocationNormalized, Router } from 'vue-router';

import { useAuthenticationStore } from '@/stores/auth';
import { useUserStore } from '@/stores/user';

import CommonPage from '../common-page';
import CommonPageName from '../common-page-name';

export default (router: Router) => {
  router.beforeEach((to: RouteLocationNormalized, _, next: NavigationGuardNext) => {
    const authStore = useAuthenticationStore();
    const userStore = useUserStore();

    if (to.name === CommonPageName.LOGIN && authStore.isLogin) {
      next({
        path: CommonPage.DASHBOARD,
        replace: true,
      });
      return;
    }

    if (!authStore.isLogin && to.name !== CommonPageName.LOGIN) {
      next({
        name: CommonPageName.LOGIN,
        replace: true,
      });
      return;
    }

    if (userStore.isFetched) {
      next();
      return;
    }
    if (authStore.isLogin) {
      userStore.fetchUserInfoAction().then(result => next(result));
    }
    next();
  });
};
